#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import connUtil
import sshCmd
import mysqlUtil
import pymysql

instConns = {1: {}, 2: {}}
instConnsTuple = {1: [], 2: []}

serverIdPorts = {}


def getServerInstConn(platform, mainConn, hefuServerId, port):
    sql = '''select url, username, password from InstMysqlConfig where id=%d''' % hefuServerId
    cursor = mainConn.cursor()
    cursor.execute(sql)
    result = cursor.fetchone()
    url = result['url']
    urlUse = url.split('''?''')[0]
    urlGood = urlUse.split('''/''')  # 最终有用的str
    username = result['username']
    password = result['password']

    db = urlGood[-1]
    ip = 'localhost'
    t = (ip, port, db)
    if t not in instConnsTuple[platform]:
        instConnsTuple[platform].append(t)
        hefuInstConn = connUtil.getHefuServerIdInstConn(ip, port, db, username, password)
        instConns[platform][hefuServerId] = hefuInstConn
    return instConns[platform][hefuServerId]


def getHefuMaps():
    ret = {}
    platforms = [1, 2]
    testConn = connUtil.getTestConn()
    sqlTemplate = '''select serverId, hefuServerId from dict_hefu_server_map where platformId=%d'''
    for platform in platforms:
        portCal = PortCal()

        hefuServerIds = []
        hefuMap = {}  # 返回

        result = mysqlUtil.mysqlCommand(testConn, sqlTemplate % platform, pymysql.cursors.DictCursor.fetchall)
        for r in result:
            hefuServerId = r['hefuServerId']
            if hefuServerId not in hefuServerIds:
                hefuServerIds.append(hefuServerId)
            sid = r['serverId']
            hefuMap[sid] = hefuServerId
        ret[platform] = hefuMap

        sorted(hefuServerIds)
        print('platform:', platform, ',hefuServerIds:', hefuServerIds)

        mapIndex = {}
        for sid in hefuServerIds:
            mapIndex[sid] = portCal.getPortIndex(platform, sid)

        serverIdPorts[platform] = mapIndex
    testConn.close()
    return ret


class PortCal:
    def __init__(self):
        self.group = 0
        self.baseIndex = 0

    def getPortIndex(self, platform, hefuServerId):
        if getGroup(hefuServerId) != self.group:
            self.baseIndex = 0
            self.group = getGroup(hefuServerId)

        if platform == 1:
            if hefuServerId > 5000:
                portIndex = 20001
            else:
                portIndex = 10016
        else:
            if hefuServerId > 4000:
                portIndex = 36501
            else:
                portIndex = 30008

        ret = portIndex + self.baseIndex
        self.baseIndex = self.baseIndex + 1
        return ret


def getGroup(hefuServerId):
    if hefuServerId > 5000:
        return 5
    if hefuServerId > 4000:
        return 4
    return 1


def queryHasMail(instConn, mailSql):
    result = mysqlUtil.mysqlCommand(instConn, mailSql, pymysql.cursors.DictCursor.fetchall)
    return len(result) > 0


def getServerIdFromPid(pid):
    serverIdStr = pid[2:5]
    # print('pid:%s, serverIdStr:%s' % (pid, serverIdStr))
    serverId = int(serverIdStr)
    if pid.startswith('15', 0, 2):
        serverId = serverId + 5000
    elif pid.startswith('24', 0, 2):
        serverId = serverId + 4000
    return serverId


# 1.建立每个服的mysql通道
# 2.查询所有九幽比赛场景, 使用ssh查询命令来得到报名所有playerid
# 3.对每一个playerid, 计算出该玩家的serverid
# 4.每个玩家查询数据库来得到是否发送过九幽报名成功邮件通知
def begin(platform):

    jiuyouLogs = []
    if platform == 1:
        jiuyouLogs.append(('123.207.252.65', (1, 2, 3, 4)))
        jiuyouLogs.append(('123.207.252.108', (1,)))
        jiuyouLogs.append(('123.207.255.117', (1, 2, 3, 4)))
        jiuyouLogs.append(('139.199.4.36', (1, 2, 3)))
    else:
        jiuyouLogs.append(('123.207.251.210', (1, 2)))

    command = '''grep -a 'jiuYouRegister' /data/logs/scene/badperson.scene.jiuyou_00%d.log.2018-04-29-[01][0-9].log --color | grep -o '"playerId":"[0-9]*"' --color | sort | uniq | awk -F ':' '{print $2}' | grep -o '[0-9]*' --color'''
    mailQueryCommand = '''select * from inst_player_mail_split_%d where playerId = %d and (mailType = 75 or mailType=76) '''

    mainConn = connUtil.getMysqlServerMainCon(platform)
    for jiuyouLog in jiuyouLogs:
        ip, sceneIds = jiuyouLog
        for sceneId in sceneIds:
            print('dealing:', ip, ',', sceneId)
            cmd = command % sceneId
            # type(out) is str
            out, err = sshCmd.doCmd(ip, cmd)
            if len(err) == 0:
                pids = out.split('\n')
                for pid in pids:
                    if len(pid) > 0:
                        serverId = getServerIdFromPid(pid)
                        pidInt = int(pid)
                        mailCmd = mailQueryCommand % ((pidInt % 20), pidInt)
                        hefuServerId = hefuMaps[platform][serverId]  # 获取合服serverid

                        port = serverIdPorts[platform][hefuServerId]  # 获取通道的端口
                        instConn = getServerInstConn(platform, mainConn, hefuServerId, port)
                        try:
                            if queryHasMail(instConn, mailCmd):
                                # print('''pid:%d register , has jiuyou Registermail check success!!!!''' % pidInt)
                                pass
                            else:
                                print('''pid:%d register , but has no jiuyou Registermail check success!!!!''' % pidInt)
                        except BaseException as e:
                            print('except', e, 'pid:', pidInt)
            else:
                print('err:', err)
    mainConn.close()


if __name__ == '__main__':
    hefuMaps = getHefuMaps()
    print('hefuMaps:', hefuMaps)

    test = [1, 2]
    for i in test:
        begin(i)
